package com.ztom.top100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 组合总和
 * <p>
 * https://leetcode-cn.com/problems/combination-sum/
 *
 * @author ZhangTao
 */
public class Code19CombinationSum {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        process(candidates, target, 0, res, new LinkedList<>());
        return res;
    }

    private void process(int[] candidates, int target, int index, List<List<Integer>> res, Deque<Integer> collect) {
        if (index == candidates.length || target < 0) {
            return;
        }
        if (target == 0) {
            res.add(new ArrayList<>(collect));
            return;
        }

        // 不要当前的数
        process(candidates, target, index + 1, res, collect);
        // 要当前的数
        if (target - candidates[index] >= 0) {
            collect.addLast(candidates[index]);
            process(candidates, target - candidates[index], index, res, collect);
            collect.pollLast();
        }
    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        // 剪枝需要排序
        Arrays.sort(candidates);
        process2(candidates, target, 0, res, new LinkedList<>());
        return res;
    }

    /**
     * 剪枝
     *
     * @param candidates
     * @param target
     * @param begin
     * @param res
     * @param collect
     */
    private void process2(int[] candidates, int target, int begin, List<List<Integer>> res, Deque<Integer> collect) {
        if (target == 0) {
            res.add(new ArrayList<>(collect));
            return;
        }

        for (int i = begin; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                break;
            }
            collect.addLast(candidates[i]);
            process2(candidates, target - candidates[i], i, res, collect);
            collect.pollLast();
        }
    }

}
